<script setup lang="ts">
import { approve, getList } from '@/api/llm/approve'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'
import useDateRangeParams from '@/hooks/useDateRangeParams'

import { usePagination } from '@/hooks/usePagination'
import { useTableHeight } from '@/hooks/useTableHeight'
import useDictStore from '@/store/modules/dict'
import { ModalShowType } from '@/types/common'
import { formatDate, omitEmptyValue } from '@/utils/common'
import apiApplicationModal from '@/views/api-manage/my-apply/api-application-modal.vue'
import Refresh from '@iconify-icons/ep/refresh'
import Search from '@iconify-icons/ep/search'
import { ElMessage, FormInstance } from 'element-plus'
import { reactive, ref } from 'vue'

const { api_apply_status } = useDictStore().getDicts('api_apply_status')
const searchParams = reactive({
  keyword: undefined,
  applyPerson: undefined,
  applyStatus: api_apply_status.getLabel('待审核'),
})
const formRef = ref<FormInstance>()
const popoverVisible = reactive({})
const applyStatus = ref('todo')
const searchDateRange = ref<[Date, Date]>([null, null])
const { dateRangeParams } = useDateRangeParams(searchDateRange, 'YYYY-MM-DD HH:mm:ss', (s, e) => ({
  submitTimeBegin: s,
  submitTimeEnd: e,
}))
const { pagination, paginationParams, changePageNumber, changePageSize } = usePagination(onSearch)
const columns: TableColumnList = [
  {
    type: 'selection',
    width: 55,
    align: 'left',
  },
  {
    label: '申请单编号',
    prop: 'applyNo',
    minWidth: 100,
  },
  {
    label: '申请单名称',
    prop: 'applyName',
    minWidth: 150,
  },
  {
    label: '申请单位',
    prop: 'applyDept',
    minWidth: 150,
  },
  {
    label: '申请人',
    prop: 'applyPerson',
    // minWidth: 150,
  },
  {
    label: '申请提交时间 ',
    prop: 'applySubmitTime',
    minWidth: 180,
    formatter: ({ applySubmitTime }) => formatDate(applySubmitTime),
  },
  {
    label: '申请状态',
    prop: 'applyStatus',
    minWidth: 100,
    formatter({ applyStatus }) {
      return api_apply_status.getLabel(applyStatus)
    },
  },
  {
    label: '审批人',
    prop: 'operatePerson',
    minWidth: 100,
  },
  {
    label: '操作时间 ',
    prop: 'operateTime',
    minWidth: 180,
    formatter: ({ operateTime }) => formatDate(operateTime),
  },
  {
    label: '操作',
    fixed: 'right',
    // width: 180,
    slot: 'operation',
  },
]
const dataList = ref([])
const loading = ref(false)
const { tableHeight, tableRef } = useTableHeight()

/** 查询列表 */
async function onSearch() {
  loading.value = true
  const { rows, total } = await getList(
    omitEmptyValue({
      ...dateRangeParams.value,
      ...paginationParams.value,
      keyword: searchParams.keyword,
      applyPerson: searchParams.applyPerson,
      applyStatus: searchParams.applyStatus,
    })
  ).finally(() => {
    loading.value = false
  })
  console.log({ rows })

  dataList.value = rows
  pagination.total = total
}

function onFilterChange(value: string) {
  if (value === 'todo') {
    searchParams.applyStatus = api_apply_status.getLabel('待审核')
  } else {
    searchParams.applyStatus = undefined
  }
  onSearch()
}

/** 重置新增的表单  */
async function resetForm() {
  searchDateRange.value = [null, null]
  formRef.value.resetFields()
  onSearch()
}

const modalShow = ref(ModalShowType.Hide)
const termId = ref<number | null>(null)

onSearch()

async function onApprove(applyId: number, approveStatus: number) {
  const { code, msg } = await approve({ applyId, approveStatus })
  if (code === 200) {
    ElMessage.success('成功')
    await onSearch()
  } else {
    ElMessage.error(`失败：${msg}`)
  }
}
</script>

<template>
  <div class="main table-view-layout">
    <el-form ref="formRef" :inline="true" :model="searchParams" class="bg-el-bg w-[99/100] pl-8 pt-4">
      <el-form-item prop="keyword">
        <el-input v-model="searchParams.keyword" placeholder="请输入申请关键词" clearable style="width: 240px"
          @keyup.enter="onSearch" />
      </el-form-item>
      <el-form-item prop="applyPerson">
        <el-input v-model="searchParams.applyPerson" placeholder="请输入申请人" clearable style="width: 240px"
          @keyup.enter="onSearch" />
      </el-form-item>
      <el-form-item label="申请提交时间">
        <el-date-picker v-model="searchDateRange" unlink-panels type="datetimerange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item prop="applyStatus">
        <el-select v-model="searchParams.applyStatus" placeholder="申请状态" clearable class="!w-[180px]"
          :disabled="applyStatus == 'todo'">
          <el-option v-for="item in api_apply_status" :key="item.value" :label="item.label" :value="item.value"
            :disabled="applyStatus == 'todo' &&
              (item.label == '审核通过' || item.label == '审核拒绝' || item.label == '已撤销')
              " />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(Search)" :loading="loading" @click="onSearch">
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm"> 重置 </el-button>
      </el-form-item>
    </el-form>
    <PureTableBar>
      <template #title>
        <div class="-mt-1">
          <el-radio-group v-model="applyStatus" @change="onFilterChange">
            <el-radio-button label="todo">待办申请</el-radio-button>
            <el-radio-button label="all">全部申请</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <template #table>
        <pure-table ref="tableRef" border align-whole="center" showOverflowTooltip table-layout="auto"
          :max-height="tableHeight" :loading="loading" :data="dataList" :columns="columns" :pagination="pagination"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)',
          }" @page-size-change="changePageSize" @page-current-change="changePageNumber">
          <template #operation="{ row }">
            <!-- <el-button link class="reset-margin" type="primary" @click="
              () => {
                modalShow = ModalShowType.View
                termId = row.applyId
              }
            ">
              查看
            </el-button> -->
            <el-popover width="320px" :visible="popoverVisible[row.applyId] === true" title="审批"
              @cancel="onApprove(row.applyId, api_apply_status.getLabel('待审核'))">
              <template #reference>
                <el-button link class="reset-margin" type="primary"
                  :disabled="row.applyStatus != api_apply_status.getLabel('待审核')"
                  @click="popoverVisible[row.applyId] = true">
                  审批
                </el-button>
              </template>
              <div class="flex">
                <el-button size="small" @click="popoverVisible[row.applyId] = false">取消</el-button>
                <el-button type="danger" size="small"
                  @click="onApprove(row.applyId, api_apply_status.getLabel('审核拒绝'))">
                  审批拒绝
                </el-button>
                <el-button type="primary" size="small"
                  @click="onApprove(row.applyId, api_apply_status.getLabel('审核通过'))">审批通过</el-button>
              </div>
            </el-popover>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <apiApplicationModal v-model:modalShow="modalShow" :term-id="termId" :on-search="onSearch" />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
</style>
